package com.codename1.samples;


import com.codename1.capture.Capture;
import com.codename1.components.InfiniteProgress;
import com.codename1.components.MediaPlayer;
import com.codename1.components.MultiButton;
import com.codename1.components.ToastBar;
import com.codename1.io.ConnectionRequest;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
import com.codename1.io.Util;
import com.codename1.media.Media;
import com.codename1.media.MediaManager;
import com.codename1.ui.ComponentGroup;
import com.codename1.ui.Container;
import com.codename1.ui.FontImage;
import com.codename1.ui.Image;
import com.codename1.ui.layouts.BorderLayout;

/**
 * This file was generated by <a href="https://www.codenameone.com/">Codename One</a> for the purpose 
 * of building native mobile applications using Java.
 */
public class VideoPlayerSample {

    private Form current;
    private Resources theme;

    public void init(Object context) {
        // use two network threads instead of one
        updateNetworkThreadCount(2);

        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if(err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });        
    }
    
    public void start() {
        if(current != null){
            current.show();
            return;
        }
        Form hi = new Form("Video Player", new BorderLayout());
        hi.add(BorderLayout.CENTER, createDemo(hi));
        hi.show();
    }

    public void stop() {
        current = getCurrentForm();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = getCurrentForm();
        }
    }
    
    public void destroy() {
    }
    
    private ConnectionRequest download;
    
    private MediaPlayer mp;
    
    public String getDisplayName() {
        return "Video";
    }

    
    
    
    public Container createDemo(Form parent) {
        MultiButton helloOnline = new MultiButton("Hello (Online)");
        MultiButton helloOffline = new MultiButton("Hello (Offline)");
        helloOnline.setTextLine2("Play thru http");
        helloOffline.setTextLine2("Download & play");
        MultiButton capture = new MultiButton("Capture Video");
        capture.setTextLine2("Record video");
        MultiButton playCapturedFile = new MultiButton("Play Captured Video");
        playCapturedFile.setTextLine2("Last capture...");
        String capturedFile = getAppHomePath() + "captured-file.mp4";
        
        FontImage.setMaterialIcon(helloOnline, FontImage.MATERIAL_VIDEO_LIBRARY);
        FontImage.setMaterialIcon(helloOffline, FontImage.MATERIAL_VIDEO_LIBRARY);
        FontImage.setMaterialIcon(capture, FontImage.MATERIAL_VIDEOCAM);
        FontImage.setMaterialIcon(playCapturedFile, FontImage.MATERIAL_PERSONAL_VIDEO);
        
        Container cnt = BoxLayout.encloseY(ComponentGroup.enclose(helloOnline, helloOffline, capture, playCapturedFile));
        cnt.setScrollableY(true);
        
        helloOffline.addActionListener(e -> {
            if(!existsInFileSystem(getAppHomePath() + "hello-codenameone.mp4")) {
                downloadFile(parent);
            } else {
                playVideo(parent, getAppHomePath() + "hello-codenameone.mp4");
            }
        });
        
        // special case: the simulator doesn't support https URLs for media due to JavaFX limitations
        if(isSimulator()) {
            helloOnline.addActionListener(e -> {
                System.out.println("Handling action event");
                playVideo(parent, "http://www.codenameone.com/files/hello-codenameone.mp4");
                
            });
        } else {
            helloOnline.addActionListener(e -> playVideo(parent, "https://www.codenameone.com/files/hello-codenameone.mp4"));
        }
        
        capture.addActionListener(e -> {
            String result = Capture.captureVideo();
            if(result != null) {
                try {
                    Util.copy(openFileInputStream(result), openFileOutputStream(capturedFile));
                } catch(IOException err) {
                    Log.e(err);
                    ToastBar.showErrorMessage("Error in copying captured file: " + err);
                }
            }
        });
        
        playCapturedFile.addActionListener(e -> {
            if(existsInFileSystem(capturedFile)) {
                playVideo(parent, capturedFile);
            } else {
                ToastBar.showErrorMessage("You need to capture a video first...");
            }
        });
        
        return cnt;
    }

    

    
    void downloadFile(final Form parent) {
        download = new ConnectionRequest("https://www.codenameone.com/files/hello-codenameone.mp4") {
            @Override
            protected void postResponse() {
                
                if(parent != getCurrentForm()) {
                    if(!Dialog.show("Download Finished", "Downloading the video completed!\nDo you want to show it now?",
                            "Show", "Later")) {
                        return;
                    }
                    parent.show();
                }
                playVideo(parent, getAppHomePath() + "hello-codenameone.mp4");
            }
        };
        download.setPost(false);
        download.setDestinationFile(getAppHomePath() + "hello-codenameone.mp4");
        ToastBar.showConnectionProgress("Downloading video", download, null, null);
        addToQueue(download);        
    }

    private void playVideo(Form parent, String videoUrl) {
        Form player = new Form(new BorderLayout());
        player.getToolbar().setBackCommand("", e -> {
            if (mp != null) {
                mp.getMedia().cleanup();
            }
            parent.showBack();
        });
        player.add(CENTER, new InfiniteProgress());
        scheduleBackgroundTask(() -> {
            try {
                Media video = MediaManager.createMedia(videoUrl, true, () -> parent.showBack());
                video.prepare();
                callSerially(() -> {
                    if (mp != null){
                        mp.getMedia().cleanup();
                    }
                    mp = new MediaPlayer(video);
                    mp.setAutoplay(true);
                    player.removeAll();
                    player.add(CENTER, mp);
                    player.revalidate();
                });
            } catch(IOException err) {
                Log.e(err);
                ToastBar.showErrorMessage("Error loading video: " + err);
            }
        });
        player.show();
    }

}
